<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class UserIdentity extends CUserIdentity {
	
	const LOGIN_TOKEN = "loginToken";
	
	private $_id;

	public function authenticate(){
		$user = Users::model()->findByAttributes( array('username'=> $this->username ) );
		
		if( $user === null )
			$this->errorCode = self::ERROR_USERNAME_INVALID;
		else if( $user->userHash !== crypt( $this->password, $user->userHash ) )
			$this->errorCode = self::ERROR_PASSWORD_INVALID;
		else{
			$this->errorCode = self::ERROR_NONE;
			$this->_id = $user->idUser;
			$this->setState( 'loginTime', date( 'Y-m-d H:i:s' ) );
			$this->setState( 'username', $user->username );
			
			/* Generate a login token and save it in the DB */
			$user->loginToken = Crypt::generateToken( $user->username );
			$user->save();
			
			/* Set the same login token in a Cookie */
			$cookieToken = new CHttpCookie( self::LOGIN_TOKEN, $user->loginToken );
			$cookieToken->expire = time() + Yii::app()->params['rememberMeTime'];
			Yii::app()->request->cookies[ self::LOGIN_TOKEN ] = $cookieToken;
			$this->setState( 'loginToken', $user->loginToken );
		}
		
		return !$this->errorCode;
	}
	
	public function getId(){
		return $this->_id;
	}
}
